package com.ph.pay.api.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.ph.config.PayConfiguration;
import com.ph.shopping.facade.pay.utils.PayecoUtils;
import com.ph.shopping.facade.pay.vo.PayVo;

/**
 * @项目：phshopping-api-pay
 * @描述：支付controller
 * @作者： 张霞
 * @创建时间： 14:29 2017/3/23
 * @Copyright @2017 by zhangxia
 */
@Controller
@RequestMapping("api/pay")
public class PayecoController {
    // 创建公共日志
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private PayConfiguration payConfiguration;
    
    
    /**
     * 易联支付接口
     * @param request
     * @param payVo 支付传入参数Vo
     * @return
     * @author Mr.Chang
     */
    @RequestMapping(value="/payeco",method= RequestMethod.POST)
    public ModelAndView payecoPay(HttpServletRequest request,HttpServletResponse response, @ModelAttribute PayVo  payVo){
    	logger.info("******************************开始跳转支付接口*********************************");
    	ModelAndView mv = new ModelAndView();
    	
        //参数校验
        if (StringUtils.isEmpty(payVo.getAmount())||StringUtils.isEmpty(payVo.getOrderNum())){
        	mv.setViewName("error/pay/payeco/error");
            mv.addObject("msg","参数解析错误!");
            return mv;
        }
        
        try{
            //获得MD5加密验签
            String mac = PayecoUtils.getMac(payVo.getAmount(), payVo.getOrderNum());
            logger.info("生成的的mac值："+mac);
            //组装支付报文
            String requestText = PayecoUtils.encryptMiWen(mac,payVo.getAmount(),request.getLocalAddr(),payVo.getDescription(),payVo.getOrderNum());
            
            //保存MD5加密验签 
//            payService.updateOrderMD5Sign(payVo.getOrderNum(), mac);
            
            logger.info("报文发送内容:"+requestText);
            logger.info("报文提交地址:"+payConfiguration.getYl_url_charge());//报文提交地址
            mv.addObject("requestText",requestText);
            mv.addObject("urlReaction",payConfiguration.getYl_url_charge());
            mv.setViewName("/pay/payeco");
        }catch (Exception e){
        	logger.error("跳转支付页面异常："+e);
        	mv.setViewName("error/pay/payeco/error");
            mv.addObject("msg","组装报文异常");
        }
        logger.info("******************************结束跳转支付接口*********************************");
        return mv;
    }

}
